package com.sibu.yx.promotion.admin.web.support.mvc;

import com.doubo.common.model.request.common.CommonRequest;
import com.doubo.common.threadlocal.SerialNo;
import com.sibu.yx.promotion.persistence.dto.UserPrincipal;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

/**
 * Created with IntelliJ IDEA.
 * User: qiujingwang
 * Date: 2016/4/28
 * Description:用于绑定moduleId的方法参数解析器(设置为当前登录会员的memberId)
 *
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor
 */
public class CustomServletModelAttributeMethodProcessor extends ServletModelAttributeMethodProcessor {
    /**
     * @-param annotationNotRequired if "true", non-simple method arguments and
     * return values are considered model attributes with or without a
     * {@code @ModelAttribute} annotation.
     */
    public CustomServletModelAttributeMethodProcessor(/*boolean annotationNotRequired*/) {
        super(true);
    }

    @Override
    protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
        //解决--限制了list最大只能增长到256
        binder.setAutoGrowCollectionLimit(2500);
        super.bindRequestParameters(binder, request);
        bindModuleId(binder);
    }

    /**
     * 绑定moduleId
     *
     * @param binder
     */
    private void bindModuleId(WebDataBinder binder) {
        Object target = binder.getTarget();
        UserPrincipal userObj = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
        if (target instanceof CommonRequest) {
            //已登录的用户
            CommonRequest commonRequest = (CommonRequest) target;

            if(userObj != null){
                Object id = userObj.getUid();
                String currentUserId = id != null ? id.toString() : "";
                commonRequest.setCurrentUserId(currentUserId);
            }
            //SerialNo.init();//设置流水号
            commonRequest.setInitiationID(SerialNo.getSerialNo());
        }
    }
}
